package com.crm.crm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.crm.domain.role.SysRole;
import com.crm.crm.domain.CluePool;
import com.crm.crm.domain.dto.UserPageQueryParam;
import com.crm.crm.domain.vo.PageResult;
import com.crm.crm.domain.vo.TreeSelectVo;
import com.crm.crm.domain.vo.UserVo;
import com.crm.crm.mapper.SystemMapper;
import com.crm.crm.mapper.UserRoleMapper;
import com.crm.crm.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, SysRole> implements UserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private SystemMapper systemMapper;
    @Override
    public PageResult<SysRole> pageQuery(UserPageQueryParam userPageQueryParams) {
        Page<SysRole> page = new Page<>(userPageQueryParams.getPageNum(), userPageQueryParams.getPageSize());
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(userPageQueryParams.getRoleName()), SysRole::getRoleName, userPageQueryParams.getRoleName())
                .like(StrUtil.isNotEmpty(userPageQueryParams.getRoleKey()), SysRole::getRoleKey, userPageQueryParams.getRoleKey())
                .eq(StrUtil.isNotEmpty(userPageQueryParams.getStatus()), SysRole::getStatus, userPageQueryParams.getStatus())
                .between(StrUtil.isNotEmpty(userPageQueryParams.getCreateTime()),
                        SysRole::getCreateTime, userPageQueryParams.getBeginTime(), userPageQueryParams.getEndTime());
        if (StringUtils.isNotEmpty(userPageQueryParams.getBeginTime())&&StringUtils.isNotEmpty(userPageQueryParams.getEndTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate beginCreatTime = LocalDate.parse(userPageQueryParams.getBeginTime(),formatter);
            LocalDate endCreatTime = LocalDate.parse(userPageQueryParams.getEndTime(),formatter);
            wrapper.between(SysRole::getCreateTime,beginCreatTime,endCreatTime);
        }
        Page<SysRole> sysRolePage = this.page(page, wrapper);
        PageResult<SysRole> pageResult = new PageResult<>(sysRolePage.getTotal(), sysRolePage.getRecords());
        return pageResult;
    }
    //保存角色菜单
    @Override
    public void saveRoleMenuIds(Long roleId, List<Long> menuIds) {

        for (Long menuId : menuIds) {
            userRoleMapper.saveRoleMenuIds(roleId,menuId);
        }
    }

}
